package com.hectopascal.auth.component;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final AntPathMatcher ANT = new AntPathMatcher();
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private JwtConfig jwtConfig;
    @Value("${security.permit-url:/backend.org.ums.user.login/")
    private String[] permitUrls;

    @Override
    @SneakyThrows
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain){
        // 1) 预检或白名单路径，直接放行
        if (isPermitted(request)) {
            chain.doFilter(request, response);
            return;
        }
        String tokenHeaderName = jwtConfig.getTokenHeader();
        String tokenHead = jwtConfig.getTokenHead();
        String authHeader = request.getHeader(tokenHeaderName);
        saveHeaders();

        if(StrUtil.isNotBlank(authHeader) && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length()).trim();
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            log.trace("checking username: {}", username);
            if (StrUtil.isNotBlank(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                String redisKey = jwtTokenUtil.getRedisKey(authToken);
                // ✅ 精简：直接构造一个 Spring Security 内置的 User
                org.springframework.security.core.userdetails.User userDetails =
                        new org.springframework.security.core.userdetails.User(
                                username,
                                "", // 密码这里可以忽略，因为 JWT 已经校验过了
                                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                        );

                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    // 2) 构造认证对象
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());

                    authentication.setDetails(
                            new WebAuthenticationDetailsSource().buildDetails(request)
                    );

                    // 3) 放到 SecurityContext 中，表示当前请求已认证
                    SecurityContextHolder.getContextHolderStrategy()
                            .getContext().setAuthentication(authentication);

                    log.trace("authenticated user: {}", username);
                }
            }
        }
        chain.doFilter(request, response);
    }

    private boolean isPermitted(HttpServletRequest request) {
        // 允许 CORS 预检
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) return true;

        String uri = request.getRequestURI(); // 例如 /login
        if (permitUrls == null) return false;

        for (String raw : permitUrls) {
            if (StrUtil.isBlank(raw)) continue;
            String pattern = raw.trim();
            if (!pattern.startsWith("/")) pattern = "/" + pattern;
            if (ANT.match(pattern, uri)) return true;
        }
        return false;
    }

    private void saveHeaders() {
        Map<String, String> headers = new HashMap<>();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            headers.put(key, value);
        }
//        FeignConfig.requestHeads.remove();
//        FeignConfig.requestHeads.set(headers);
    }
}
